<?php
// +----------------------------------------------------------------------
// | 中犇单商户
// +----------------------------------------------------------------------
// | Copyright (c) 2019-2021 中犇科技 All rights reserved.
// +----------------------------------------------------------------------

namespace app\user\admin;

use app\admin\admin\Base;
use app\user\export\MoneylogExport;
use app\user\model\MoneyLog;
use app\user\model\User;
use app\user\model\User as UserModel;
use app\user\model\VirtualMoneyLog;
use think\Db;
use service\Format;
use app\common\model\Order;

/**
 * 财务统计
 * Class Finance
 * @package app\user\admin
 * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
 * @since 2019/4/3 16:02
 */
class Finance extends Base
{

    /**
     * 充值消费
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     * @created 2019/5/9 9:35
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function money_log()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);
        // 查询
        $map = $this->getMap();        // 排序
        $order = $this->getOrder('user_money_log.aid DESC');

        //导出excel
        if (isset($map['export']) && $map['export'] == 1) {
            unset($map['export']);
            $MoneylogExport = new MoneylogExport();
            $MoneylogExport->export($map);
        }

        $data_list = MoneyLog::getAllList($map, $order);

        $types = ['全部'] + MoneyLog::$types;
        $fields = [
            ['aid', lang('序号')],
            ['user_id', lang('会员').'ID'],
            ['user_nickname', lang('会员名称')],
            ['mobile', lang('手机号')],
            ['before_money', lang('变动前金额')],
            ['change_money', lang('变动金额'), 'callback', function ($item) {
                if ($item > 0) {
                    $item = '+' . $item;
                }
                return $item;
            }],
            ['after_money', lang('变动后金额')],
            ['change_type', lang('类型'), '', '', $types],
            ['create_time', lang('变动时间')],
            ['remark', lang('备注')],
        ];
        
        $search_fields = [
            ['user_nickname', lang('昵称'), 'text'],
            ['mobile', lang('手机号'), 'text'],
            ['change_type', lang('类型'), 'select', '', $types],
            ['create_time', lang('变动时间'), 'daterange'],
        ];
        //统计充值金额
        $recharge = MoneyLog::where('change_type', 1)->sum('change_money');
        //总计收入
        $spend = MoneyLog::where('change_money', '>',0)->sum('change_money');
        //总计支出
        $change = MoneyLog::where('change_money', '<',0)->sum('change_money');
        //统计提现金额
        $withdraw = MoneyLog::where('change_type', 'in', '4,5')->sum('change_money');
        //统计收益金额
       // $salary = MoneyLog::where('change_type', 10)->sum('change_money');
        //统计变动金额
        unset($map['export']);
  
        $statistics = [];
        $statistics[] = ['message' => '总计累加','colmd' => '2', 'label' => '元', 'number'=> $spend];  
        $statistics[] = ['message' => '总计减少','colmd' => '2', 'label' => '元', 'number'=> $change];
        $statistics[] = ['message' => '用户充值金额','colmd' => '2', 'label' => '元', 'number'=> $recharge];
        $statistics[] = ['message' => '共计提现金额','colmd' => '2', 'label' => '元', 'number'=> $withdraw];

        $this->assign('excel_show', 1);

        return Format::ins()
            ->hideCheckbox()
            ->setTopSearch($search_fields)
            ->addColumns($fields)
            ->setData($data_list)
            ->setPageStatistics($statistics)
            ->setTopButton(['title' => lang('手动充值余额'), 'href' => ['add'], 'icon' => 'fa fa-plus pr5', 'class' => 'btn btn-sm mr5 btn-primary '])
            ->fetch();
    }

    public function virtual_log()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);
        // 查询
        $map = $this->getMap();        // 排序
        $order = $this->getOrder('user_virtual_log.aid DESC');

        $data_list = VirtualMoneyLog::getAllList($map, $order);

        $types = VirtualMoneyLog::$types;
        $fields = [
            ['aid', lang('序号')],
            ['user_id', lang('会员').'ID'],
            ['user_nickname', lang('会员名称')],
            ['before_money', lang('变动虚拟币')],
            ['change_money', lang('变动虚拟币')],
            ['after_money', lang('变动后虚拟币')],
            ['change_type', lang('类型'), '', '', $types],
            ['create_time', lang('变动时间')],
            ['remark', lang('备注')],
        ];

        return Format::ins()
            ->hideCheckbox()
            ->addColumns($fields)
            ->setTopButton(['title' => lang('手动充值余额'), 'href' => ['add'], 'icon' => 'fa fa-plus pr5', 'class' => 'btn btn-sm mr5 btn-success '])
            ->setTopButton(['title' => lang('手动充值虚拟币'), 'href' => ['virtual_add'], 'icon' => 'fa fa-plus pr5', 'class' => 'btn btn-sm mr5 btn-success '])
            ->setTopButton(['title' => lang('余额消费记录'), 'href' => ['money_log'], 'icon' => 'fa fa-list pr5', 'class' => 'btn btn-sm mr5 btn-success '])
            ->setData($data_list)
            ->fetch();
    }

    public function add_integral()
    {
        // 保存文档数据
        if ($this->request->isAjax()) {
            $data = $this->request->post();
      
            try {
                $user = User::where('id', $data['user_id'])->lock(true)->field('id,score,user_money')->find();
                if (!$user) {
                    throw new \Exception(lang('会员不存在'));
                }
                if(!$data['money']){
                    throw new \Exception(lang('请输入数额'));
                }                
                $money = bcadd($data['money'],0,2);
                if( bccomp($data['money'], $money ,2) != 0){
                    throw new \Exception(lang('数额校验不正确'));
                }
                $after = bcadd($data['money'], $user['score'], 2);
                if(strlen($after) > 11){
                    throw new \Exception(lang('充值数额溢出'));
                }   
                $ordeNo = get_order_sn('CZ');
                $ret = \app\user\model\ScoreLog::change($user["id"], $money, 6, "管理员操作，工号".UID ,$ordeNo);
                if (!$ret) {
                    throw new \Exception(lang('更新会员金额失败'));
                }              
            } catch (\Exception $e) {
              
                $this->error($e->getMessage());
            }
            $this->success(lang('充值成功'));
        }
        /*  $fields = [
              ['type' => 'text', 'name' => 'user_id', 'title' => '会员ID'],
              ['type' => 'text', 'name' => 'money', 'title' => lang('充值金额')],
          ];*/
        $this->assign('page_title', lang('手动充值'));
        /*  $this->assign('form_items', $fields);*/
        return $this->fetch('add_integral');
    }

    /**
     * 手动充值余额
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     * @created 2019/5/9 9:36
     * @return mixed
     */
    public function add()
    {
        // 保存文档数据
        if ($this->request->isAjax()) {
            $data = $this->request->post();
            //验证数据
            $result = $this->validate($data,'Finance');
            if (true !== $result) {
                $this->error($result);
            }
            if ($data['user_id'] == '') {
                $this->error(lang('请选择会员'));
            }
            if ($data['money'] == '') {
                $this->error(lang('请输入数额'));
            }
            if (mb_strlen($this->trimAll($data['money']), 'utf8') > 8) {
                $this->error(lang('充值金额过大， 最大为99999999'));
            };
            if ($data['remark'] == '') {
                $this->error(lang('请输入充值理由'));
            }
     
            try {                                
                $user = User::where('id', $data['user_id'])->lock(true)->field('id,user_money')->find();
                if (!$user) {
                    throw new \Exception(lang('会员不存在'));
                }
                if(!$data['money']){
                    throw new \Exception(lang('请输入数额'));
                }
                $money = bcadd($data['money'],0,2);
                if( bccomp($data['money'], $money ,2) != 0){
                    throw new \Exception(lang('数额校验不正确'));
                }
                $after = bcadd($data['money'], $user['user_money'], 2);
                if(strlen($after) > 11){
                    throw new \Exception(lang('充值数额溢出'));
                }      
                
                $remark = lang('系统充值余额') . $money . lang('，').lang('操作管理员工号').':' . UID. ',充值理由：'.$data['remark'];
                $ordeNo = get_order_sn('CZ');
            
                $ret = MoneyLog::changeMoney($user['id'], $user['user_money'], $money, 3, $remark, $ordeNo);
                if (!$ret) {
                    throw new \Exception(lang('更新会员金额失败'));
                }
           
            } catch (\Exception $e) {
          
                $this->error($e->getMessage());
            }
            $this->success(lang('充值成功'));
        }
        /*  $fields = [
              ['type' => 'text', 'name' => 'user_id', 'title' => '会员ID'],
              ['type' => 'text', 'name' => 'money', 'title' => lang('充值金额')],
          ];*/

        $this->assign('page_title', lang('手动充值'));
        /*  $this->assign('form_items', $fields);*/
        return $this->fetch('add');
    }

    /**
     * 手动充值虚拟币
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     * @created 2019/5/9 9:36
     * @return mixed
     */
    public function virtual_add()
    {
        // 保存文档数据
        if ($this->request->isAjax()) {
            $data = $this->request->post();
      
            try {
                $user = User::where('id', $data['user_id'])->lock(true)->field('id,user_virtual_money')->find();
           
                if (!$user) {
                    throw new \Exception(lang('会员不存在'));
                }
                if(!$data['money']){
                    throw new \Exception(lang('请输入数额'));
                }
                $money = bcadd($data['money'],0,2);
                if( bccomp($data['money'], $money ,2) != 0){
                    throw new \Exception(lang('数额校验不正确'));
                }
                $after = bcadd($data['money'], $user['user_virtual_money'], 2);
                if(strlen($after) > 11){
                    throw new \Exception(lang('充值数额溢出'));
                }      
                $remark = lang('系统充值虚拟币') . $money . '，'.lang('操作管理员工号').':' . UID;
                $ordeNo = get_order_sn('CZ');           
                $ret = VirtualMoneyLog::changeMoney($user['id'], $user['user_virtual_money'], $money, 3, $remark, $ordeNo);
                if (!$ret) {
                    throw new \Exception(lang('更新会员金额失败'));
                }        
            } catch (\Exception $e) {          
                $this->error($e->getMessage());
            }
            $this->success(lang('充值成功'));
        }
        $fields = [
            ['type' => 'text', 'name' => 'user_id', 'title' => '会员ID'],
            ['type' => 'text', 'name' => 'money', 'title' => lang('充值金额')],
        ];

        $this->assign('page_title', lang('手动充值虚拟币'));
        $this->assign('form_items', $fields);
        return $this->fetch('admin@public/add');
    }


    public function searchUser()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 查询
        $key = input('key/s', '');
        if ($key == '') {
            return '';
        }
        $page = input('page/d', 1);
        // 数据列表
        $data_list = UserModel::where('id', 'like', '%' . $key . '%')
            ->whereOr('user_name', 'like', '%' . $key . '%')
            ->whereOr('user_nickname', 'like', '%' . $key . '%')
            ->whereOr('mobile', 'like', '%' . $key . '%')
            ->field('id,user_name,user_nickname,mobile')
            ->paginate(20);
        $results = [];
        foreach ($data_list as $v) {
            $str = $v['id'] . '/' . $v['user_name'] . '/' . $v['user_nickname'] . '/' . $v['mobile'];
            $results[] = ['id' => $v['id'], 'text' => $str];
        }
        $data['results'] = $results;
        $data['pagination'] = $data_list->currentPage() == $data_list->lastPage() ? ['more' => true] : ['more' => false];
        return json($data, JSON_UNESCAPED_UNICODE);
    }
}
